<script setup lang="ts">
import { ref } from 'vue';
import { NModal, NCard, NButton, NSpace, NSpin } from 'naive-ui';
import { fetchOpsInstanceLogs, downloadOpsInstanceLogs } from '@/service/api';

const visible = ref(false);
const loading = ref(false);
const instanceId = ref<number>(0);
const logs = ref('');

const open = async (id: number) => {
  instanceId.value = id;
  visible.value = true;
  await loadLogs();
};

const loadLogs = async () => {
  loading.value = true;
  try {
    logs.value = await fetchOpsInstanceLogs(instanceId.value);
  } catch (error) {
    window.$message?.error('加载日志失败');
  } finally {
    loading.value = false;
  }
};

const handleDownload = () => {
  const url = downloadOpsInstanceLogs(instanceId.value);
  window.open(url, '_blank');
};

const handleRefresh = () => {
  loadLogs();
};

const handleClose = () => {
  visible.value = false;
  logs.value = '';
};

defineExpose({
  open
});
</script>

<template>
  <NModal v-model:show="visible" preset="card" title="实例日志" class="w-1000px">
    <template #header-extra>
      <NSpace>
        <NButton size="small" @click="handleRefresh">
          <icon-mdi-refresh class="mr-4px text-icon" />
          刷新
        </NButton>
        <NButton size="small" type="primary" @click="handleDownload">
          <icon-mdi-download class="mr-4px text-icon" />
          下载
        </NButton>
      </NSpace>
    </template>

    <NSpin :show="loading">
      <div class="h-600px overflow-auto bg-gray-900 text-green-400 p-12px rounded font-mono text-sm">
        <pre class="whitespace-pre-wrap">{{ logs || '暂无日志' }}</pre>
      </div>
    </NSpin>
  </NModal>
</template>

<style scoped></style>
